package GSEA::FileReading::FileReader;

use strict;
use warnings ;

sub constrFileReader($$$) #constructor
{
	my ($classe , $L_file_name , $S_file_name  ) = @_; 
	
	
	if( !defined($L_file_name) 		){ die("argument 'L_file_name' is not set , error");}
	if( !defined($S_file_name) 		){ die("argument 'S_file_name' is not set , error");}

	
	my $this = {
					"L_file_name"	=> $L_file_name	,
					"S_file_name"	=> $S_file_name	
				};
	
	bless ($this,$classe);  
		
	return $this;  
}

sub set_Lfile($$)
{
	( my $this , my $newLfile ) = @_ ;
	$this->{"L_file_name"} = $newLfile ;
}

sub set_Sfile($$)
{
	( my $this , my $newSfile ) = @_ ;
	$this->{"S_file_name"} = $newSfile ;
}

sub read_Lfile($)
{
	( my $this ) = @_ ;
	
	my @L_table	; 
	my $L_file	= $this->{"L_file_name"};

	if( -e $L_file )
	{
		if( ! open(L_FILE , "<$L_file") ) { die("huh.. error happened when trying to open '$L_file' ! $! "); }
		
		my $line = "";
		my $counter = 0 ;
		while(<L_FILE>)
		{
			$counter++;
			$line = $_ ; 
			chomp($line);
	
			( my $gene_id , my $rank ) = split( /\t/ , $line) ;
			
			##verifying unicity of the gene
			for( my $i=0 ; $i< @L_table ; $i++)
			{
				if( @{ $L_table[$i] }[0] eq $gene_id )
				{
					die("error : gene '$gene_id' was found at least 2 times in the file '$L_file' (line $counter and line".($i+1).")"); 
				}
			}
			
			push(@L_table , [ $gene_id , $rank ] );
		}
		
		close(L_FILE);
	}
	else
	{
		die("file '$L_file' does not exist ! $! ");
	}
	
	## sort the L_table
	my @liste = sort { @{ $b  }[1] <=> @{ $a  }[1] }  @L_table;@L_table = @liste ;
	
	#print("\n L_file ($L_file) readen , ".@L_table." genes found.");	
	return @L_table ;
}


sub read_Sfile($)
{
	( my $this ) = @_ ;
	
	my @S_table	; 
	my $S_file	= $this->{"S_file_name"};


	if( -e $S_file )
	{
		if( ! open(S_FILE , "<$S_file") ) { die("huh.. error happened when trying to open '$S_file' ! $! "); }
		
		my $line = "";
		my $counter = 0 ;
		while(<S_FILE>)
		{
			$counter++;
			$line = $_ ;chomp($line);
	
			my $gene_id = $line ;
			
			##verifying unicity of the gene
			for( my $i=0 ; $i< @S_table ; $i++)
			{
				if( $S_table[$i]  eq $gene_id )
				{
					die("error : gene '$gene_id' was found at least 2 times in the file '$S_file' (line $counter and ".($i+1).")"); 
				}
			}
			
			push(@S_table , $gene_id );
		}
		
		close(S_FILE);
	}
	
	#print("\n L_file ($S_file) readen , ".@S_table." genes found.");
	return @S_table ;	
}


1;
